package com.ruoyi.system.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.AwPlanConfig;
import com.ruoyi.system.service.IAwPlanConfigService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : anxinr
 * @date : 2023/8/15 11:03
 */
@Slf4j
@Component
public class StartPlanManager {

    public static final String BLANK_STRING = " " ;

    @Autowired
    private IAwPlanConfigService configService ;


    /**
     * 重新设置配置文件内容
     * 通过计划id
     * @param id
     */
    public void resetConfigFileInfoByStartPlanId(Long id) throws IOException {
        LambdaQueryWrapper<AwPlanConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AwPlanConfig::getStartPlanId ,id) ;
        List<AwPlanConfig> list = configService.list(wrapper);
        Collection<String> values = list.stream().filter(c->c.getState().equals(0L)).collect(Collectors.toMap(AwPlanConfig::getConfig, AwPlanConfig::getConfig)).values() ;
        StringBuilder sb = new StringBuilder();
        for (String value : values) {
            sb.append(value).append(BLANK_STRING) ;
        }
        File file = new File(new File("").getCanonicalPath() + "/config/cfg.ini");
        if (!file.exists()) {
            log.info("启动配置不存在，采用默认配置");
            new File(file.getParent()).mkdirs();
            try{
                boolean newFile = file.createNewFile();
                if (!newFile) {
                    log.info("创建启动配置文件失败！");
                    throw new IOException("创建启动配置文件失败！") ;
                }
                file = new File(new File("").getCanonicalPath() + "/config/cfg.ini");
                FileUtil.writeAsString(file ,sb.toString());
            }catch (IOException e){
                log.info("创建启动配置文件异常,异常信息为 -> {}" ,e.getMessage());
                throw e ;
            }
        }else {
            FileUtil.writeAsString(file ,sb.toString());
        }
    }






    /**
     * 追加新配置到配置文件中
     * @param config
     * @throws IOException
     */
    public static void appendConfigToConfigFile(String config) throws IOException {
        File file = new File(new File("").getCanonicalPath() + "/config/cfg.ini");
        if (!file.exists()) {
            log.info("启动配置不存在，采用默认配置");
            new File(file.getParent()).mkdirs();
            try{
                boolean newFile = file.createNewFile();
                if (!newFile) {
                    log.info("创建启动配置文件失败！");
                    throw new IOException("创建启动配置文件失败！") ;
                }
                file = new File(new File("").getCanonicalPath() + "/config/cfg.ini");
                String startConfigInfo = FileUtil.readAsString(file);
                startConfigInfo = startConfigInfo + config ;
                FileUtil.writeAsString(file ,startConfigInfo);
            }catch (IOException e){
                log.info("创建启动配置文件异常,异常信息为 -> {}" ,e.getMessage());
                throw e ;
            }
        }else {
            String startConfigInfo = FileUtil.readAsString(file);
            if (StringUtils.isNotBlank(startConfigInfo)) {
                startConfigInfo = startConfigInfo + StartPlanManager.BLANK_STRING + config ;
                FileUtil.writeAsString(file ,startConfigInfo);
            }else {
                FileUtil.writeAsString(file ,config);
            }
        }
    }

    /**
     * 跟换旧配置，并且保存到配置中
     * @param oldConfig
     * @param newConfig
     * @return
     */
    public static void replaceOldConfig(String oldConfig ,String newConfig) throws IOException {
        File file = new File(new File("").getCanonicalPath() + "/config/cfg.ini");
        if (!file.exists()) {
            log.info("启动配置不存在，采用默认配置");
            new File(file.getParent()).mkdirs();
            try{
                boolean newFile = file.createNewFile();
                if (!newFile) {
                    log.info("创建启动配置文件失败！");
                    throw new IOException("创建启动配置文件失败！") ;
                }
                file = new File(new File("").getCanonicalPath() + "/config/cfg.ini");
                String startConfigInfo = FileUtil.readAsString(file);
                FileUtil.writeAsString(file ,startConfigInfo.replace(oldConfig ,newConfig));
            }catch (IOException e){
                log.info("创建启动配置文件异常,异常信息为 -> {}" ,e.getMessage());
                throw e ;
            }
        }else {
            String startConfigInfo = FileUtil.readAsString(file);
            if (StringUtils.isNotBlank(startConfigInfo)) {
                FileUtil.writeAsString(file ,startConfigInfo.replace(oldConfig ,newConfig));
            }else {
                FileUtil.writeAsString(file ,startConfigInfo.replace(oldConfig ,newConfig));
            }
        }
    }

    /**
     * 获取配置文件内容
     * @return String
     */
    public static String getConfigFileContent() throws IOException {
        File file = new File(new File("").getCanonicalPath() + "/config/cfg.ini");
        if (!file.exists()) {
            new File(file.getParent()).mkdirs();
            try{
                boolean newFile = file.createNewFile();
                if (!newFile) {
                    log.info("创建启动配置文件失败！");
                    throw new IOException("创建启动配置文件失败！") ;
                }
                file = new File(new File("").getCanonicalPath() + "/config/cfg.ini");
                FileUtil.writeAsString(file ,"");
                return "" ;
            }catch (IOException e){
                log.info("创建启动配置文件异常,异常信息为 -> {}" ,e.getMessage());
                throw e ;
            }
        }else {
            String startConfigInfo = FileUtil.readAsString(file);
            if (StringUtils.isNotBlank(startConfigInfo)) {
                return startConfigInfo ;
            }else {
                return "" ;
            }
        }
    }
}
